var md5 = require('../wxParse/md5.js');
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
function wxpay(url, wxcode, openid, money, hunterid, proId, order_time, formId){
  var app = getApp();
  var nonceStr = ''   //随机字符串，后台返回
  var prepayId = ''    //预支付id，后台返回
  var paySign = ''     //加密字符串
  var randomOrderId=''
  var timestamp = String(Date.parse(new Date()))   //时间戳

  post(url, { code: wxcode, openid: openid, totalfee: money,ordescId: proId,}, function (res) {

    if (res.code != "200") {
      app.alert("微信请求失败");
      return;
    }
    randomOrderId = res.data.randomOrderId
    nonceStr = res.data.nonceStr
    prepayId = res.data.prepayId
    // 按照字段首字母排序组成新字符串
    var payDataA = "appId=" + res.data.appid + "&nonceStr=" + nonceStr + "&package=prepay_id=" + prepayId + "&signType=MD5&timeStamp=" + timestamp;
    var payDataB = payDataA + "&key=" + res.data.appKey;
    // 使用MD5加密算法计算加密字符串
    paySign = md5.MD5(payDataB).toUpperCase();
    // 发起微信支付
    wx.requestPayment({
      'timeStamp': timestamp,
      'nonceStr': nonceStr,
      'package': 'prepay_id=' + prepayId,
      'signType': 'MD5',
      'paySign': paySign,
      'success': function (res) {
        // 保留当前页面，跳转到应用内某个页面，使用wx.nevigeteBack可以返回原页面
        post(app.api.addOrder, { openid: openid, unionid: app.globalData.unionid, ordercode: randomOrderId, hunterId: hunterid, ordescId: proId, orderMoney: money, orderTime: order_time, formId }, function (res) {

        });
        wx.navigateTo({
          url: '../payResult/payResult?status=1'
        })
      },
      'fail': function (res) {
        wx.navigateTo({
          url: '../payResult/payResult?status=0'
        })
      }
    });

  });
}

function post(url, data, callback) {
  wx.request({
// url: "https://www.headoffer.com/tnl-wxapp/" + url,
url: "https://www.tiaonali.com/tnl-wxapp/" + url,
// url: "http://localhost:8000/tnl-wxapp/" + url,
    data: data,
    method: 'POST',
    dataType: 'json',
    header: { "content-type": "application/x-www-form-urlencoded" },
    success: function (res) {
      if(res.statusCode!==200){
        // wx.showToast({
        //   title:'服务无响应，请刷新重试',
        //   icon:'none'
        // })
      }else{
        callback(res.data)
      }
    },
    fail: function (res) {
    },
    complete: function (res) {
    }
  })
}

function request(url, data = {}, method = "POST") {
  return new Promise(function (resolve, reject) {
    wx.request({
    //  url: "https://www.headoffer.com/tnl-wxapp/" + url,
     url: "https://www.tiaonali.com/tnl-wxapp/" + url,
    //  url: "http://localhost:8000/tnl-wxapp/"+url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Nideshop-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.statusCode == 200) {

          if (res.data.errno == 401) {
            //需要登录后才可以操作

          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
        reject(err)
   
      }
    })
  });
}

function date_format_time(unixtime) {
  var dateTime = new Date(parseInt(unixtime))
  var year = dateTime.getFullYear();
  var month = dateTime.getMonth() + 1;
  var day = dateTime.getDate();
  var now = new Date();
  var now_new = Date.parse(now.toDateString()); //typescript转换写法
  var milliseconds = now_new - dateTime;
  var timeSpanStr = year + '-' + month + '-' + day;
  return timeSpanStr;
 }


// 显示繁忙提示
var showBusy = text => wx.showToast({
    title: text,
    icon: 'loading',
    duration: 10000
})

// 显示成功提示
var showSuccess = text => wx.showToast({
    title: text,
    icon: 'success'
})

// 显示失败提示
var showModel = (title, content) => {
    wx.hideToast();

    wx.showModal({
        title,
        content: JSON.stringify(content),
        showCancel: false
    })
}

module.exports = { wxpay,formatTime, showBusy, showSuccess, showModel,request,post, date_format_time}
